package com.gxa.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxa.common.LayR;
import com.gxa.common.R;
import com.gxa.mapper.EmpMapper;
import com.gxa.mapper.emplRoleMapper;
import com.gxa.param.MyTableParam;
import com.gxa.pojo.Empl;
import com.gxa.pojo.EmplRole;
import com.gxa.service.EmplService;
import com.gxa.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;

/**
 * @author xiejinfeng
 * @create 2021-06-09 21:29
 * @descrip:
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class EmplServiceImpl implements EmplService{

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private emplRoleMapper emplRoleMapper;

    @Override
    public LayR list(MyTableParam param) {

        PageHelper.startPage(param.getPage(),param.getLimit());

        List<Empl> empls = empMapper.findAll(param);

        PageInfo<Empl> emplPageInfo = new PageInfo<>(empls);

        return new LayR(0,"success",emplPageInfo.getList(),emplPageInfo.getTotal());
    }

    @Override
    public LayR updatestatus(Empl empl) {

        empMapper.update(empl);
        return new LayR(200,"success");
    }

    @Override
    public R add(Empl empl, String[] roleIds) {

        empl.setEmplPwd(MD5Util.MD55(empl.getEmplPwd()));

        empl.setCreateTime(new Timestamp(System.currentTimeMillis()));

        empMapper.save(empl);

        for (String roleId : roleIds) {
            EmplRole emplRole = new EmplRole(empl.getId(), Integer.valueOf(roleId));
            emplRoleMapper.save(emplRole);
        }

        return new R(200,"添加成功");
    }

    @Override
    public R edit(Empl empl, String[] roleIds) {

        empMapper.update(empl);

        for (String roleId : roleIds) {
            EmplRole emplRole = new EmplRole(empl.getId(), Integer.valueOf(roleId));
            emplRoleMapper.update(emplRole);
        }

        return new R(200,"修改成功");
    }


    @Override
    public R deleteAll(String[] ids) {

        empMapper.deleteAll(ids);
        return new R(200,"删除成功");
    }

    @Override
    public R deleteOne(Integer id) {
        empMapper.deleteOneById(id);
        return new R(200,"删除成功");
    }

    @Override
    public R findById(Integer id) {
        Empl byPk = empMapper.findByPk(id);

        return new R(200,"success",byPk);
    }
}
